package com.permission.service.impl;

import com.permission.dao.UserDao;
import com.permission.model.PageResult;
import com.permission.model.User;
import com.permission.service.UserService;
import com.permission.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class UserServiceImpl implements UserService {

    @Override
    public User getUserWithRolesByUsername(String username) {
        try (SqlSession session = MyBatisUtil.getSession()) {
            UserDao userDao = session.getMapper(UserDao.class);
            return userDao.selectUserWithRolesByUsername(username);
        }
    }

    @Override
    public PageResult<User> getUsersWithRolesAndMenus(
            String loginname, String email, Integer status,
            int pageNum, int pageSize) {
        try (SqlSession session = MyBatisUtil.getSession()) {
            UserDao userDao = session.getMapper(UserDao.class);
            int start = (pageNum - 1) * pageSize;
            List<User> users = userDao.selectUsersWithRolesAndMenus(loginname, email, status, start, pageSize);
            int total = userDao.countUsers(loginname, email, status);
            return new PageResult<>(total, users, pageNum, pageSize);
        }
    }

    @Override
    public User getUserById(Long id) {
        try (SqlSession session = MyBatisUtil.getSession()) {
            UserDao userDao = session.getMapper(UserDao.class);
            return userDao.selectUserById(id);
        }
    }

    @Override
    public void updateUserRoles(Long userId, List<Long> roleIds) {
        SqlSession session = MyBatisUtil.getSession();
        try {
            UserDao userDao = session.getMapper(UserDao.class);
            // 先删除原有角色关系
            userDao.deleteUserRoles(userId);
            // 新增角色关系
            if (roleIds != null && !roleIds.isEmpty()) {
                for (Long roleId : roleIds) {
                    userDao.insertUserRole(userId, roleId);
                }
            }
            session.commit();
        } catch (Exception e) {
            session.rollback();
            throw new RuntimeException("更新用户角色失败", e);
        } finally {
            session.close();
        }
    }
}